import { saveStorageToken, saveStorageUser } from "@/utils/storage";
import { getUserInfo, doLogout } from "@/service/shop";

export default {
  namespaced: true,
  state: {
      userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
      token: JSON.parse(localStorage.getItem('token')) || '',
  },
  getters: {
    userInfo: state => state.userInfo,
  },
  mutations: {
    setStoreUser(state, data) {
      state.userInfo = data;
      saveStorageUser(data);
    },
    setStoreToken(state, data) {
      state.token = data;
      saveStorageToken(data);
    },
  },
  actions: {
    async getUserInfoData({ state, commit }, data) {
      const res = await getUserInfo(state.userInfo?.id);
      const { code, info } = res || {};
      if (code !== 1) return;
      commit('setStoreUser', info);
    },
    async doLogoutData({ commit, state }) {
      const res = await doLogout(state.userInfo?.id);
      commit('setStoreUser', null);
      commit('setStoreToken', '');
    },
  },
};